import React from "react";

import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import Button from "antd/lib/button";
import Col from "antd/lib/col";
import Radio from "antd/lib/radio";
import Divider from "antd/lib/divider";
import DatePicker from "antd/lib/date-picker";
import Row from "antd/lib/row";
import Table from "antd/lib/table";
import Menu from "antd/lib/menu";
import Dropdown from "antd/lib/dropdown";
import ConfigProvider from "antd/lib/config-provider";
import Layout from "antd/lib/layout";
import AutoComplete from "antd/lib/auto-complete";
import locale from 'antd/es/date-picker/locale/zh_CN';
import zhCN from 'antd/es/locale/zh_CN';
import Alert from "@/services/alert";
import { currentUser } from "@/services/auth";
import routes from "@/services/routes";
import moment from "moment";
import QueryShowField from "@/services/queryshowfield";
import { AppstoreFilled, DownOutlined, UpOutlined } from "@ant-design/icons";
import CreateQueryShowFieldDialog from "@/components/enums/QueryShowFieldDialog";

const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}

class Alerts2List extends React.Component {
  state = {
    page: 1,
    pagesize: localStorage.getItem("alerts2listpagesize") ? (localStorage.getItem("alerts2listpagesize") !== undefined ? Number(localStorage.getItem("alerts2listpagesize")) : 20) : 20,
    total: 1,
    order: 1,
    loading: false,
    isread: localStorage.getItem("alerts2listisread") ? (localStorage.getItem("alerts2listisread") !== undefined ? Number(localStorage.getItem("alerts2listisread")) : 1) : 1,
    name:localStorage.getItem("alerts2listname") ? (localStorage.getItem("alerts2listname") !== undefined ? localStorage.getItem("alerts2listname"): "") : "",
    bill_date: [moment().startOf('year'),moment()],
    data: [],
    queryshowfielddata: [],
    showall: false,
  };
  componentWillMount() {
    this.fieldsshowload();
    let param = {
      page: this.state.page,
      pagesize: this.state.pagesize,
      isread: this.state.isread,
      name:"",
    }
    this.seldata(param);
  }
  fieldsshowload = () => {
    QueryShowField.getbycode("alertslist1").then(data => {
      this.setState({
        queryshowfielddata: data,
      });
    });
  }
  isEmptyobj = (str) => {
    if (str === '' || str === null || str === 'null' || str === undefined || str === 'undefined') {
      return true;
    } else {
      return false;
    }
  }
  seldata = (params = {}) => {
    this.setState({ loading: true });
    if(!this.isEmptyobj(this.state.bill_date)){
      if(this.state.bill_date.length===2){
        params.begindate=this.state.bill_date[0].format('YYYY-MM-DD');
        params.enddate=this.state.bill_date[1].format('YYYY-MM-DD');
      }
    }
    Alert.query(params).then(data => {
      this.setState({
        loading: false,
        data: data.data,
        page: params.page,
        pagesize: params.pagesize,
        total: data.total,
        field: params.field,
        order: params.order,
      });
    });
  };

  handlesel = (index) => {
    let param = {
      page: 1,
      pagesize: this.state.pagesize,
      isread: this.state.isread,
      name: this.state.name,
    }
    this.seldata(param);
  };

  handleTableChange = (pagination, filters, sorter) => {
    localStorage.setItem("alerts2listpagesize", pagination.pageSize);
    let field = sorter.field;
    let order = 0;
    if (sorter.order === "descend") {
      order = 1;
    }
    let param = {
      field: field,
      order: order,
      page: pagination.current,
      pagesize: this.state.pagesize,
      isread: this.state.isread,
      name: this.state.name,
    }
    this.seldata(param);
  };
  handlefieldshow = () => {
    CreateQueryShowFieldDialog.showModal({ queryshowfield: this.state.queryshowfielddata })
      .onClose((result = {}) => {
        if (result.success) {
          this.fieldsshowload();
        }
      }).onDismiss(() => {
      });
  }
  handleclear = () => {
    this.setState({
      name: "",
      isread: 0,
    });
    localStorage.setItem("alerts2listisread", 0);
    localStorage.setItem("alerts2listname", "");
  }
  onDragEnter = info => {
    window.console.log(info);
  };
  readAlert=record =>{
    this.alertbatchread({id:record.id,type:'read'});
  }
  handlebatch =type =>{
    let ids="0";
    this.state.data.forEach((item) => {
      ids =ids + ","+item.id;
    });
    this.alertbatchread({id:ids,type:type});
  }
  alertbatchread=params=>{
    Alert.read(params).then(data => {
      let item = {
        order: this.state.order,
        page: this.state.page,
        pagesize: this.state.pagesize,
        isread: this.state.isread,
        name: this.state.name,
      }
      this.seldata(item);
    });
  }
  deleteAlert=record =>{
    Alert.delete(record).then(data => {
      let param = {
        order: this.state.order,
        page: this.state.page,
        pagesize: this.state.pagesize,
        isread: this.state.isread,
        name: this.state.name,
      }
      this.seldata(param);
    });
  }
  render() {
    const paginationProps = {
      showSizeChanger: true,
      total: this.state.total, // 数据总数
      pageSize: parseInt(this.state.pagesize), // 每页条数
      current: parseInt(this.state.page), // 当前页码
      pageSizeOptions: ["10", "20", "30", "100"],
      showTotal: ((total) => {
        return `共 ${total} 条`;
      }),
    };
    let listcolumns = [];

    if (this.state.queryshowfielddata.fieldsshow !== undefined) {
      (this.state.queryshowfielddata.fieldsshow || []).map(item => {
        let items = this.state.queryshowfielddata.fieldsall.filter((p) => {
          return p.key === item;
        });
        if (items.length > 0) {
          listcolumns.push({
            title: items[0].title,
            dataIndex: item,
            key: item,
            sorter: (a, b) => a[item] > b[item] ? 1 : -1
          })
        }
        return item;
      }
      );
    }
    listcolumns.push({
      title: '操作',
      key: 'action',
      render: (record) => (
        <span>
          <Button size="small">
          <a className="clickable" onClick={() => this.readAlert(record)}>{record.isread ? "未读":"已读" }</a>
          </Button>&nbsp;&nbsp;
          <Button size="small" >
            <a className="clickable" onClick={() => this.deleteAlert(record)}>删除</a>
          </Button>
        </span>
      ),
    });
    return (
      <ConfigProvider locale={zhCN}>
        <div style={{ width: "400px", height: "60px" }}>
          <div style={{ width: "20px", height: "50px", float: "left" }}>
          </div>
          <div style={{ width: "50px", height: "50px", float: "left" }}>
            <img src="/static/images/projectlist.png" alt="HR" loading="lazy" />
          </div>
          <div style={{ width: "320px", height: "30px", float: "left" }}>
            <h3 style={{ margin: "7px", padding: "0" }}>{"提醒列表"}</h3>
          </div>
        </div>
        <Layout>
          <Layout style={{ padding: '0 24px 24px' }}>
            {this.state.showall && (<><Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                日期:</div></Col>
              <Col span={6}>
                <DatePicker.RangePicker
                  locale={locale}
                  style={{ width: "100%" }}
                  value={this.state.bill_date}
                  onChange={value => {
                    localStorage.setItem("customerneedlistbill_date", value);
                    this.setState({
                      bill_date: value,
                    });
                  }}
                  placeholder="日期"
                  autoFocus
                />
              </Col>
            </Row></>)}
              <Row style={{ marginBottom: 5 }}>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  类型:</div></Col>
                <Col span={6}>
                  <Radio.Group onChange={e => {
                      localStorage.setItem("alerts2listisread", e.target.value);
                      this.setState({
                        isread: e.target.value,
                      });
                    }}
                    style={{ width: "100%" }}
                    value={this.state.isread}>
                    <Radio value={0}>所有</Radio>
                    <Radio value={1}>未读</Radio>
                    <Radio value={2}>已读</Radio>
                  </Radio.Group>
                </Col>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  名称:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={this.state.name}
                    onChange={value => {
                      localStorage.setItem("alerts2listname", value);
                      this.setState({ name: value });
                    }}
                    placeholder="名称"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                  </AutoComplete>
                </Col>
                <Col span={8}>
                  <Divider type="vertical" />
                  <Button type="primary" onClick={() => this.handlesel(1)} >
                    <i className="fa fa-search m-r-5" />
                    查询
                  </Button>
                  <Divider type="vertical" />
                  <Button onClick={() => this.handleclear()} >
                    清空
                  </Button>
                  <Divider type="vertical" />
                  <Button onClick={() => { this.setState({ showall: !this.state.showall }); }} >
                    {this.state.showall && (<UpOutlined />)}
                    {!this.state.showall && (<DownOutlined />)}
                    {this.state.showall ? '默认' : '更多'}
                  </Button>
                </Col>
              </Row>
              <Row style={{ marginBottom: 5 }}>
                <Col span={10}>
                 <Button type="primary" onClick={() => this.handlebatch("read")} >
                    <i className="fa fa-check m-r-5" />
                    全部已读
                  </Button>
                  <Divider type="vertical" />
                  <Button type="primary" onClick={() => this.handlebatch("delete")} >
                    <i className="fa fa-times m-r-5" />
                    全部删除
                  </Button>
                  <Divider type="vertical" />
                  <Dropdown
                    trigger={["click"]}
                    overlay={
                      <Menu>
                        {currentUser.hasPermission("fieldshow") && (
                          <Menu.Item key="delete-item">
                            <a onMouseUp={() => this.handlefieldshow()}>显示隐藏列</a>
                          </Menu.Item>
                        )}
                      </Menu>
                    }>
                    <Button type="primary" style={{ margin: "10px" }} data-test="CreateButton" >
                      <AppstoreFilled />更多功能
                    </Button>
                  </Dropdown>
                </Col>
              </Row>
              <div>
                <Table rowKey='num'
                  rowClassName={(record, index) => getRowClassName(record, index)}
                  columns={listcolumns}
                  scroll={{ x: 'max-content' }}
                  dataSource={this.state.data}
                  pagination={paginationProps}
                  loading={this.state.loading}
                  onChange={this.handleTableChange}
                />
              </div>
            </Layout>
        </Layout>
      </ConfigProvider>
    );
  }
}

routes.register(
  "Alerts2.List",
  routeWithUserSession({
    path: "/alerts2",
    title: "提醒",
    render: pageProps => <Alerts2List {...pageProps} />,
  })
);
